<template>
  <div class="account-settings">
    <t-card title="账号设置" class="settings-card">
      <t-tabs v-model="activeTab" placement="left" class="settings-tabs">
        <!-- 基本信息 -->
        <t-tab-panel value="basic" label="基本信息">
          <div class="tab-content">
            <t-form 
              :data="basicForm" 
              :rules="basicRules"
              ref="basicFormRef"
              label-width="120px"
              @submit="handleBasicSubmit"
            >
              <t-row :gutter="24">
                <t-col :span="12">
                  <t-form-item label="用户名" name="username">
                    <t-input 
                      v-model="basicForm.username" 
                      placeholder="请输入用户名"
                      :disabled="!editMode.basic"
                    />
                  </t-form-item>
                </t-col>
                <t-col :span="12">
                  <t-form-item label="真实姓名" name="realName">
                    <t-input 
                      v-model="basicForm.realName" 
                      placeholder="请输入真实姓名"
                      :disabled="!editMode.basic"
                    />
                  </t-form-item>
                </t-col>
              </t-row>
              
              <t-row :gutter="24">
                <t-col :span="12">
                  <t-form-item label="邮箱地址" name="email">
                    <t-input 
                      v-model="basicForm.email" 
                      placeholder="请输入邮箱地址"
                      :disabled="!editMode.basic"
                    />
                  </t-form-item>
                </t-col>
                <t-col :span="12">
                  <t-form-item label="手机号码" name="phone">
                    <t-input 
                      v-model="basicForm.phone" 
                      placeholder="请输入手机号码"
                      :disabled="!editMode.basic"
                    />
                  </t-form-item>
                </t-col>
              </t-row>
              
              <t-row :gutter="24">
                <t-col :span="12">
                  <t-form-item label="部门" name="department">
                    <t-select 
                      v-model="basicForm.department" 
                      placeholder="请选择部门"
                      :disabled="!editMode.basic"
                    >
                      <t-option value="admin" label="管理部门" />
                      <t-option value="operation" label="运营部门" />
                      <t-option value="customer" label="客服部门" />
                      <t-option value="finance" label="财务部门" />
                    </t-select>
                  </t-form-item>
                </t-col>
                <t-col :span="12">
                  <t-form-item label="职位" name="position">
                    <t-input 
                      v-model="basicForm.position" 
                      placeholder="请输入职位"
                      :disabled="!editMode.basic"
                    />
                  </t-form-item>
                </t-col>
              </t-row>
              
              <t-form-item label="个人简介" name="bio">
                <t-textarea 
                  v-model="basicForm.bio" 
                  placeholder="请输入个人简介"
                  :maxlength="200"
                  :disabled="!editMode.basic"
                />
              </t-form-item>
              
              <t-form-item>
                <t-space>
                  <t-button 
                    v-if="!editMode.basic" 
                    theme="primary" 
                    @click="editMode.basic = true"
                  >
                    编辑信息
                  </t-button>
                  <template v-else>
                    <t-button 
                      theme="primary" 
                      type="submit"
                      :loading="saving.basic"
                    >
                      保存修改
                    </t-button>
                    <t-button 
                      variant="outline" 
                      @click="cancelBasicEdit"
                    >
                      取消
                    </t-button>
                  </template>
                </t-space>
              </t-form-item>
            </t-form>
          </div>
        </t-tab-panel>

        <!-- 安全设置 -->
        <t-tab-panel value="security" label="安全设置">
          <div class="tab-content">
            <!-- 修改密码 -->
            <t-card title="修改密码" class="security-card">
              <t-form 
                :data="passwordForm" 
                :rules="passwordRules"
                ref="passwordFormRef"
                label-width="120px"
                @submit="handlePasswordSubmit"
              >
                <t-form-item label="当前密码" name="currentPassword">
                  <t-input 
                    v-model="passwordForm.currentPassword" 
                    type="password"
                    placeholder="请输入当前密码"
                  />
                </t-form-item>
                
                <t-form-item label="新密码" name="newPassword">
                  <t-input 
                    v-model="passwordForm.newPassword" 
                    type="password"
                    placeholder="请输入新密码"
                  />
                </t-form-item>
                
                <t-form-item label="确认密码" name="confirmPassword">
                  <t-input 
                    v-model="passwordForm.confirmPassword" 
                    type="password"
                    placeholder="请再次输入新密码"
                  />
                </t-form-item>
                
                <t-form-item>
                  <t-button 
                    theme="primary" 
                    type="submit"
                    :loading="saving.password"
                  >
                    修改密码
                  </t-button>
                </t-form-item>
              </t-form>
            </t-card>

            <!-- 两步验证 -->
            <t-card title="两步验证" class="security-card">
              <div class="security-item">
                <div class="security-info">
                  <h4>短信验证</h4>
                  <p>通过短信接收验证码，提高账号安全性</p>
                </div>
                <t-switch 
                  v-model="securitySettings.smsAuth" 
                  @change="handleSecurityChange('smsAuth')"
                />
              </div>
              
              <t-divider />
              
              <div class="security-item">
                <div class="security-info">
                  <h4>邮箱验证</h4>
                  <p>通过邮箱接收验证码，提高账号安全性</p>
                </div>
                <t-switch 
                  v-model="securitySettings.emailAuth" 
                  @change="handleSecurityChange('emailAuth')"
                />
              </div>
            </t-card>

            <!-- 登录记录 -->
            <t-card title="最近登录记录" class="security-card">
              <t-table 
                :data="loginHistory" 
                :columns="loginColumns"
                row-key="id"
                :pagination="false"
                size="small"
              />
            </t-card>
          </div>
        </t-tab-panel>

        <!-- 通知设置 -->
        <t-tab-panel value="notification" label="通知设置">
          <div class="tab-content">
            <t-card title="通知偏好" class="notification-card">
              <div class="notification-group">
                <h4>系统通知</h4>
                <div class="notification-item">
                  <div class="notification-info">
                    <span>系统维护通知</span>
                    <small>接收系统维护和更新通知</small>
                  </div>
                  <t-switch 
                    v-model="notificationSettings.systemMaintenance" 
                    @change="handleNotificationChange"
                  />
                </div>
                
                <div class="notification-item">
                  <div class="notification-info">
                    <span>安全警告</span>
                    <small>接收账号安全相关警告</small>
                  </div>
                  <t-switch 
                    v-model="notificationSettings.securityAlert" 
                    @change="handleNotificationChange"
                  />
                </div>
              </div>
              
              <t-divider />
              
              <div class="notification-group">
                <h4>业务通知</h4>
                <div class="notification-item">
                  <div class="notification-info">
                    <span>订单通知</span>
                    <small>接收新订单和订单状态变更通知</small>
                  </div>
                  <t-switch 
                    v-model="notificationSettings.orderNotification" 
                    @change="handleNotificationChange"
                  />
                </div>
                
                <div class="notification-item">
                  <div class="notification-info">
                    <span>用户反馈</span>
                    <small>接收用户反馈和评价通知</small>
                  </div>
                  <t-switch 
                    v-model="notificationSettings.userFeedback" 
                    @change="handleNotificationChange"
                  />
                </div>
              </div>
              
              <t-divider />
              
              <div class="notification-group">
                <h4>通知方式</h4>
                <t-radio-group 
                  v-model="notificationSettings.method" 
                  @change="handleNotificationChange"
                >
                  <t-radio value="email">仅邮箱通知</t-radio>
                  <t-radio value="sms">仅短信通知</t-radio>
                  <t-radio value="both">邮箱和短信</t-radio>
                  <t-radio value="none">关闭通知</t-radio>
                </t-radio-group>
              </div>
            </t-card>
          </div>
        </t-tab-panel>

        <!-- 隐私设置 -->
        <t-tab-panel value="privacy" label="隐私设置">
          <div class="tab-content">
            <t-card title="隐私控制" class="privacy-card">
              <div class="privacy-item">
                <div class="privacy-info">
                  <h4>个人信息可见性</h4>
                  <p>控制其他用户能看到的个人信息范围</p>
                </div>
                <t-select 
                  v-model="privacySettings.profileVisibility" 
                  @change="handlePrivacyChange"
                >
                  <t-option value="public" label="公开" />
                  <t-option value="team" label="仅团队成员" />
                  <t-option value="private" label="私有" />
                </t-select>
              </div>
              
              <t-divider />
              
              <div class="privacy-item">
                <div class="privacy-info">
                  <h4>活动状态显示</h4>
                  <p>是否显示在线状态和最后活动时间</p>
                </div>
                <t-switch 
                  v-model="privacySettings.showActivity" 
                  @change="handlePrivacyChange"
                />
              </div>
              
              <t-divider />
              
              <div class="privacy-item">
                <div class="privacy-info">
                  <h4>数据收集</h4>
                  <p>允许系统收集使用数据以改善服务</p>
                </div>
                <t-switch 
                  v-model="privacySettings.dataCollection" 
                  @change="handlePrivacyChange"
                />
              </div>
            </t-card>

            <!-- 数据导出 -->
            <t-card title="数据管理" class="privacy-card">
              <div class="data-management">
                <div class="data-item">
                  <div class="data-info">
                    <h4>导出个人数据</h4>
                    <p>下载您在系统中的所有个人数据</p>
                  </div>
                  <t-button 
                    variant="outline" 
                    @click="exportPersonalData"
                    :loading="exporting"
                  >
                    导出数据
                  </t-button>
                </div>
                
                <t-divider />
                
                <div class="data-item">
                  <div class="data-info">
                    <h4>删除账号</h4>
                    <p class="danger-text">永久删除账号和所有相关数据，此操作不可恢复</p>
                  </div>
                  <t-button 
                    theme="danger" 
                    variant="outline"
                    @click="showDeleteConfirm = true"
                  >
                    删除账号
                  </t-button>
                </div>
              </div>
            </t-card>
          </div>
        </t-tab-panel>
      </t-tabs>
    </t-card>

    <!-- 删除账号确认对话框 -->
    <t-dialog
      v-model:visible="showDeleteConfirm"
      header="确认删除账号"
      :confirm-btn="{ content: '确认删除', theme: 'danger' }"
      @confirm="handleDeleteAccount"
    >
      <div class="delete-confirm">
        <t-icon name="error-circle" size="48px" style="color: #e34d59; margin-bottom: 16px;" />
        <p><strong>警告：此操作不可恢复！</strong></p>
        <p>删除账号将会：</p>
        <ul>
          <li>永久删除您的个人信息</li>
          <li>清除所有操作记录</li>
          <li>取消所有权限和角色</li>
          <li>无法恢复任何数据</li>
        </ul>
        <p>请输入您的用户名以确认删除：</p>
        <t-input 
          v-model="deleteConfirmText" 
          placeholder="请输入用户名确认"
        />
      </div>
    </t-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { MessagePlugin } from 'tdesign-vue-next'

const userStore = useUserStore()

// 当前激活的标签页
const activeTab = ref('basic')

// 编辑模式
const editMode = reactive({
  basic: false
})

// 保存状态
const saving = reactive({
  basic: false,
  password: false
})

// 基本信息表单
const basicForm = reactive({
  username: '',
  realName: '',
  email: '',
  phone: '',
  department: '',
  position: '',
  bio: ''
})

// 基本信息表单备份（用于取消编辑）
const basicFormBackup = reactive({})

// 基本信息验证规则
const basicRules = {
  username: [
    { required: true, message: '请输入用户名' },
    { min: 2, max: 20, message: '用户名长度为2-20个字符' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址' },
    { type: 'email', message: '请输入正确的邮箱格式' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' }
  ]
}

// 密码表单
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码验证规则
const passwordRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码' },
    { min: 6, max: 20, message: '密码长度为6-20个字符' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码' },
    {
      validator: (val) => val === passwordForm.newPassword,
      message: '两次输入的密码不一致'
    }
  ]
}

// 安全设置
const securitySettings = reactive({
  smsAuth: false,
  emailAuth: true
})

// 通知设置
const notificationSettings = reactive({
  systemMaintenance: true,
  securityAlert: true,
  orderNotification: true,
  userFeedback: false,
  method: 'email'
})

// 隐私设置
const privacySettings = reactive({
  profileVisibility: 'team',
  showActivity: true,
  dataCollection: true
})

// 登录记录
const loginHistory = ref([
  {
    id: 1,
    ip: '192.168.1.100',
    location: '贵州省贵阳市',
    device: 'Chrome 120.0 / Windows 10',
    time: '2024-01-15 14:30:25',
    status: '成功'
  },
  {
    id: 2,
    ip: '192.168.1.101',
    location: '贵州省贵阳市',
    device: 'Chrome 120.0 / Windows 10',
    time: '2024-01-15 09:15:10',
    status: '成功'
  },
  {
    id: 3,
    ip: '10.0.0.50',
    location: '贵州省遵义市',
    device: 'Safari 17.0 / macOS',
    time: '2024-01-14 16:45:30',
    status: '失败'
  }
])

// 登录记录表格列
const loginColumns = [
  { colKey: 'ip', title: 'IP地址', width: 140 },
  { colKey: 'location', title: '登录地点', width: 120 },
  { colKey: 'device', title: '设备信息', ellipsis: true },
  { colKey: 'time', title: '登录时间', width: 160 },
  { 
    colKey: 'status', 
    title: '状态', 
    width: 80,
    cell: (h, { row }) => {
      return h('t-tag', {
        theme: row.status === '成功' ? 'success' : 'danger',
        variant: 'light'
      }, row.status)
    }
  }
]

// 删除账号相关
const showDeleteConfirm = ref(false)
const deleteConfirmText = ref('')
const exporting = ref(false)

// 表单引用
const basicFormRef = ref()
const passwordFormRef = ref()

// 初始化数据
const initializeData = () => {
  // 从用户store获取基本信息
  const currentUser = userStore.currentUser
  if (currentUser) {
    Object.assign(basicForm, {
      username: currentUser.username || '',
      realName: currentUser.realName || '',
      email: currentUser.email || '',
      phone: currentUser.phone || '',
      department: currentUser.department || '',
      position: currentUser.position || '',
      bio: currentUser.bio || ''
    })
  }
  
  // 备份原始数据
  Object.assign(basicFormBackup, basicForm)
}

// 处理基本信息提交
const handleBasicSubmit = async ({ validateResult }) => {
  if (validateResult === true) {
    saving.basic = true
    
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1500))
      
      // 更新用户store
      userStore.updateUserInfo(basicForm)
      
      // 更新备份数据
      Object.assign(basicFormBackup, basicForm)
      
      editMode.basic = false
      MessagePlugin.success('基本信息更新成功')
    } catch (error) {
      MessagePlugin.error('更新失败，请重试')
    } finally {
      saving.basic = false
    }
  }
}

// 取消基本信息编辑
const cancelBasicEdit = () => {
  Object.assign(basicForm, basicFormBackup)
  editMode.basic = false
}

// 处理密码修改
const handlePasswordSubmit = async ({ validateResult }) => {
  if (validateResult === true) {
    saving.password = true
    
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 2000))
      
      // 清空表单
      Object.assign(passwordForm, {
        currentPassword: '',
        newPassword: '',
        confirmPassword: ''
      })
      
      MessagePlugin.success('密码修改成功')
    } catch (error) {
      MessagePlugin.error('密码修改失败，请重试')
    } finally {
      saving.password = false
    }
  }
}

// 处理安全设置变更
const handleSecurityChange = async (type) => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    MessagePlugin.success('安全设置已更新')
  } catch (error) {
    MessagePlugin.error('设置更新失败')
  }
}

// 处理通知设置变更
const handleNotificationChange = async () => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    MessagePlugin.success('通知设置已更新')
  } catch (error) {
    MessagePlugin.error('设置更新失败')
  }
}

// 处理隐私设置变更
const handlePrivacyChange = async () => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    MessagePlugin.success('隐私设置已更新')
  } catch (error) {
    MessagePlugin.error('设置更新失败')
  }
}

// 导出个人数据
const exportPersonalData = async () => {
  exporting.value = true
  
  try {
    // 模拟数据导出
    await new Promise(resolve => setTimeout(resolve, 3000))
    
    // 创建下载链接（实际应该是从服务器获取文件）
    const data = {
      user: basicForm,
      settings: {
        security: securitySettings,
        notification: notificationSettings,
        privacy: privacySettings
      },
      exportTime: new Date().toISOString()
    }
    
    const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `personal-data-${Date.now()}.json`
    a.click()
    URL.revokeObjectURL(url)
    
    MessagePlugin.success('个人数据导出成功')
  } catch (error) {
    MessagePlugin.error('数据导出失败')
  } finally {
    exporting.value = false
  }
}

// 删除账号
const handleDeleteAccount = async () => {
  if (deleteConfirmText.value !== basicForm.username) {
    MessagePlugin.error('用户名输入不正确')
    return
  }
  
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    MessagePlugin.success('账号删除请求已提交，将在24小时内处理')
    showDeleteConfirm.value = false
    deleteConfirmText.value = ''
  } catch (error) {
    MessagePlugin.error('删除请求提交失败')
  }
}

// 组件挂载时初始化数据
onMounted(() => {
  initializeData()
})
</script>

<style scoped>
.account-settings {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.settings-card {
  max-width: 1200px;
  margin: 0 auto;
}

.settings-tabs {
  min-height: 600px;
}

.tab-content {
  padding: 20px;
}

.security-card,
.notification-card,
.privacy-card {
  margin-bottom: 20px;
}

.security-item,
.notification-item,
.privacy-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
}

.security-info,
.notification-info,
.privacy-info {
  flex: 1;
}

.security-info h4,
.notification-info span,
.privacy-info h4 {
  margin: 0 0 4px 0;
  font-weight: 500;
}

.security-info p,
.notification-info small,
.privacy-info p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.notification-group {
  margin-bottom: 24px;
}

.notification-group h4 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 500;
}

.data-management {
  padding: 0;
}

.data-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 0;
}

.data-info {
  flex: 1;
}

.data-info h4 {
  margin: 0 0 8px 0;
  font-weight: 500;
}

.data-info p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.danger-text {
  color: #e34d59 !important;
}

.delete-confirm {
  text-align: center;
  padding: 20px;
}

.delete-confirm ul {
  text-align: left;
  margin: 16px 0;
  padding-left: 20px;
}

.delete-confirm li {
  margin: 8px 0;
  color: #666;
}

:deep(.t-tabs__content) {
  padding: 0;
}

:deep(.t-card__body) {
  padding: 24px;
}

:deep(.t-form-item__label) {
  font-weight: 500;
}
</style>
